package org.ggn.scoreanalyze.util;

import org.ggn.scoreanalyze.model.ScorePanel;
import org.ggn.scoreanalyze.model.Student;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/** 文件处理工具类
 * Created by guin_guo on 2015/12/13.
 */
public class FileUtils {
    private static String FileUrl = null;

    /**
     * 打开文件的方法
     * @return
     */
    public static ScorePanel OpenFile() {
        //打开文件
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {}
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            FileUrl = chooser.getSelectedFile().toString();
        }

        //读取文件
        ScorePanel panel;
        if (FileUrl != null) {
            Scanner scanner;
            try {
                scanner = new Scanner(new FileInputStream(FileUrl),"utf8");
            } catch (FileNotFoundException e) {
                FileUtils.showMsg("找不到文件");
                return null;
            }
            panel = new ScorePanel();
            Student student ;
            List<Student> students = new ArrayList<Student>();
            ObjectInputStream ois = null;
            if (FileUrl.endsWith(".txt") || FileUrl.endsWith(".TXT")) {
                try {
                    while (scanner.hasNext()) {
                        String context = scanner.nextLine();
                        String[] datas = context.split(",");
                        student = new Student(datas[0], datas[1], Integer.parseInt(datas[2]));
                        students.add(student);
                    }
                } catch (NumberFormatException e) {
                    FileUtils.showMsg("文件格式不正确");
                    return null;
                } catch (ArrayIndexOutOfBoundsException e) {
                    FileUtils.showMsg("文件格式不正确");
                    return null;
                }
            } else if (FileUrl.endsWith(".score") || FileUrl.endsWith(".SCORE")) {
                try {
                    ois = new ObjectInputStream(new FileInputStream(FileUrl));
                    student = (Student) ois.readObject();
                    while (student!= null) {
                        students.add(student);
                        student = (Student) ois.readObject();
                    }
                } catch (IOException e) {
                } catch (ClassNotFoundException e) {
                    FileUtils.showMsg("文件读取错误");
                    return null;
                } finally {
                    try {
                        ois.close();
                    } catch (IOException e) {
                    }
                }
            } else {
                FileUtils.showMsg("文件格式错误");
                return null;
            }
            try {
                String[] name = chooser.getSelectedFile().getName().split("-");
                panel.setClazz(name[0]);
                panel.setName(name[1].substring(0,name[1].indexOf(("."))-1));
            } catch (Exception e) {
                FileUtils.showMsg("文件名不符合要求");
            }
            panel.setFilePath(chooser.getSelectedFile().getPath());
            panel.setStudents(students);
            panel.deal();
        } else {
            FileUtils.showMsg("文件不存在");
            return null;
        }
        panel.getDatas();
        return panel;
    }

    /**
     * 保存文件的方法
     * @param scorePanel
     * @param type
     * @return
     */
    public static boolean saveFile(ScorePanel scorePanel,String type) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {}
        JFileChooser chooser = new JFileChooser();
        File original = new File(scorePanel.getFilePath());
        chooser.setCurrentDirectory(original);
        chooser.setSelectedFile(original);
        int status = chooser.showSaveDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
            String newPath = chooser.getSelectedFile().getPath();
            FileOutputStream fos = null;
            ObjectOutputStream oos = null;
            OutputStreamWriter writer = null;
            Writer out = null;
            if (type.equals("txt")) { //二进制文件的保存
                if (!newPath.endsWith(".txt") & !newPath.endsWith(".TXT")) {
                    newPath += ".txt";
                }
                try {
                    fos = new FileOutputStream(newPath);
                    out = new OutputStreamWriter(fos, "UTF-8");
                    for (Student student1 : scorePanel.getStudents()) {
                        out.write((student1.toString()+"\r"));
                    }
                    out.flush();
                    FileUtils.showMsg("保存文件成功！文件地址：" + newPath);
                    return true;
                } catch (IOException e) {
                    FileUtils.showMsg("保存文件失败");
                    return false;
                } finally {
                    try {
                        fos.close();
                        out.close();
                    } catch (IOException e) {
                        FileUtils.showMsg("系统发生异常");
                    }
                }

            } else if (type.equals("score")) { //对象文件的保存
                if (!newPath.endsWith(".score") & !newPath.endsWith(".SCORE")) {
                    if (newPath.contains(".txt")) {
                        newPath = newPath.replace(".txt", "");
                    }
                    newPath += ".score";
                }
                try {
                    oos = new ObjectOutputStream(new FileOutputStream(newPath));
                    for (Student s : scorePanel.getStudents()) {
                        oos.writeObject(s);
                    }
                    FileUtils.showMsg("保存文件成功！文件地址：" + newPath);
                    return true;
                } catch (IOException e) {
                    FileUtils.showMsg("保存文件失败");
                    return false;
                } finally {
                    try {
                        oos.close();
                    } catch (IOException e) {
                        FileUtils.showMsg("系统发生异常");
                    }
                }
            }
        }
        return false;
    }

    /**
     * 弹窗,提示信息为msg
     * @param msg
     */
    public static void showMsg(String msg) {
        Object[] options = { "确定", "取消" };
        JOptionPane.showOptionDialog(null, msg, "Warning",
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                null, options, options[0]);
    }
}
